#include <Carbon/Carbon.h>
#include <OpenGL/OpenGL.h>
#include <AGL/agl.h>

#include "evas_gl_common.h"

#include "evas_common.h"
#include "evas_private.h"
#include "evas_engine.h"
#include "Evas_Engine_GL_Quartz.h"

static Evas_GL_Quartz_Window *_evas_gl_quartz_window = NULL;

static AGLContext context = NULL;
static WindowRef window;

GLint _evas_gl_quartz_configuration[5] = { AGL_RGBA,
                                           AGL_DOUBLEBUFFER,
                                           AGL_DEPTH_SIZE, 24,
                                           AGL_NONE };

void
eng_window_make_current(WindowRef window)
{
   context = NULL;
   AGLPixelFormat myAGLPixelFormat;

   myAGLPixelFormat = aglChoosePixelFormat(NULL, 0, _evas_gl_quartz_configuration);

   if(myAGLPixelFormat)
      context = aglCreateContext(myAGLPixelFormat, NULL);

   aglSetWindowRef(context, window);
   aglSetCurrentContext(context);
}


Evas_GL_Quartz_Window *
eng_window_new(WindowRef   win,
 int      w,
 int      h)
{
   Evas_GL_Quartz_Window *gw;

   gw = calloc(1, sizeof(Evas_GL_Quartz_Window));
   if (!gw) return NULL;
   gw->win = win;

	window = gw->win;
    
   eng_window_make_current(window);
   ShowWindow(window);
   gw->context = context;
   gw->gl_context = evas_gl_common_context_new();
   if (!gw->gl_context)
   {
      aglSetCurrentContext(NULL);
      aglDestroyContext(gw->context);
      gw->context = NULL;
      free(gw);
      return NULL;
   }
   evas_gl_common_context_resize(gw->gl_context, w, h);
   return gw;
}

void
eng_window_free(Evas_GL_Quartz_Window *gw)
{
   if (gw == _evas_gl_quartz_window) _evas_gl_quartz_window = NULL;
   evas_gl_common_context_free(gw->gl_context);
   
   aglSetCurrentContext(NULL);
   aglDestroyContext(gw->context);
   
   free(gw);
}

void
eng_window_use(Evas_GL_Quartz_Window *gw)
{
   ShowWindow(window);
   if (_evas_gl_quartz_window != gw)
   {
      _evas_gl_quartz_window = gw;
      aglSetCurrentContext(context);
   }
   evas_gl_common_context_use(gw->gl_context);
}
